package cc.greencat.gcmall.product.service.impl;

import cc.greencat.gcmall.common.consts.GcMallConst;
import cc.greencat.gcmall.common.utils.PageUtils;
import cc.greencat.gcmall.common.utils.Query;
import cc.greencat.gcmall.product.dao.CategoryDao;
import cc.greencat.gcmall.product.entity.CategoryEntity;
import cc.greencat.gcmall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> productCategoryEntities = baseMapper.selectList(null);
        return productCategoryEntities.stream()
                .filter(category -> Objects.equals(category.getParentCid(), GcMallConst.GcMallProduct.CATEGORY_ROOT_PARENT_ID))
                .map(category -> {
                    category.setChildren(this.getChildren(category, productCategoryEntities));
                    return category;
                })
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }

    private List<CategoryEntity> getChildren(CategoryEntity parentCategory, List<CategoryEntity> categoryEntities) {
        if (Objects.isNull(parentCategory)) {
            return Lists.newArrayList();
        }
        return categoryEntities.stream()
                .filter(category -> Objects.equals(category.getParentCid(), parentCategory.getCatId()))
                .filter(Objects::nonNull)
                .map(category -> {
                    category.setChildren(this.getChildren(category, categoryEntities));
                    return category;
                }).sorted(Comparator.comparing(CategoryEntity::getSort))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}